<template>
  <div class="login">
    <van-form  @submit="login" show-error-message>
  <van-field
    v-model="formData.phone"
    placeholder="手机号"
    :rules="[{ required: true, message: '请填写正确的手机号' }]"
  />
  <van-field
    v-model="formData.pass"
    type="password"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写正确的密码' }]"
  />
  <div style="margin: 20px auto; width: 50%; height: 50px; display: flex; justify-content: space-around;">
    <!-- <van-button round block type="info" native-type="login" size="small">登录</van-button> -->
    <van-button type="info" native-type="login">登录</van-button>
    <van-button type="primary" @click="registerRouter">注册</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';
import { user_login } from '../utils/api';
import { mapActions } from 'vuex';
export default {
  data(){
    return{
      formData:{
        phone:'',
        pass:''
      }
    }
  },
  methods:{
    login(){
    if(/^1[3|9|5]\d{9}$/.test(this.formData.phone) == false){
      Toast.fail("输入合法手机号")
    }else if(!this.formData.pass){
      Toast.fail("请输入密码")
    }else{//验证通过
      user_login(this.formData).then((res)=>{
        if(res.data.code == 200){
          //保存用户信息，token
          localStorage.setItem('token',res.data.token);
          localStorage.setItem('userinfo',JSON.stringify(res.data.userinfo));
          
         
          console.log("登录成功");
           //调用vuex异步方法，请求当前用户的收藏列表
          this.$store.dispatch('request_favlist');
          //调用vuex异步方法，请求当前用户的购物车列表
          this.$store.dispatch('request_shopcartlist');
          //调用vuex异步方法请求用户的收货地址列表
          this.$store.dispatch('request_addresslist');
          this.$router.push('/');
         
        }else{
          Toast.fail('登录失败')
        }
      })
    }
  },
  registerRouter(){
    this.$router.push('/register');
  }
}
}
</script>

<style lang='scss' scoped>
.login{
  margin: 50px 20px;
}
.login .title{
  font-weight: bold;
  text-align: center;
  line-height: 40px;
}
.login .block{
  margin: 20px 0;
}
.login .block input{
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding-left: 20px;
  box-sizing: border-box;
  outline: none;
  width: 100%;
}
</style>